package com.luguotao.lease.web.custom.interceptor;

import com.luguotao.lease.common.context.LoginUser;
import com.luguotao.lease.common.context.LoginUserContext;
import com.luguotao.lease.common.exception.LeaseException;
import com.luguotao.lease.common.result.ResultCodeEnum;
import com.luguotao.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    /*
     *  /admin/info
     *  拦截器前端项目发送的请求----> 判断请求是否合法(是否登录(有没有合法的token))
     *
     *  tomcat: web容器
     *    3大作用域: 请求域 会话域  应用域
     *
     * */

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String accessToken = request.getHeader("access_token");
//token为空，返回未登陆
        if (accessToken == null){
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }else {
            //判断是否过期
            Claims claims = JwtUtil.parseToken(accessToken);
            Long userId = claims.get("userId", Long.class);
            String userName = claims.get("userName", String.class);

            //可以放到请求域
//            request.setAttribute("userId",userId);

            //把负载数据存储到线程中
            LoginUserContext.setUser(new LoginUser(userId,userName));
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUserContext.removeUser();
    }
}
